<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/5/22
 * Time: 19:39
 */

namespace iBrand\Shop\Server\Http\Controllers;


use Carbon\Carbon;
use iBrand\Component\Discount\Repositories\CouponRepository;
use iBrand\Component\User\Models\User;
use iBrand\Server\Http\Controllers\Controller;

class CouponController extends Controller
{

    protected $couponRepository;

    public function __construct(CouponRepository $couponRepository)
    {
        $this->couponRepository = $couponRepository;
    }

    /**
     * 店员扫码之后获取优惠券信息
     * @return \Dingo\Api\Http\Response
     */
    public function getCouponDetail()
    {
        $couponID = request('coupon_id');
        $userID = request('user_id');

        $coupon = $this->couponRepository->getCouponDetails($couponID, $userID);
        $user = User::find($userID);

        return $this->api(['coupon' => $coupon, 'user' => $user]);
    }

    /**
     * 核销优惠券动作
     * @return \Dingo\Api\Http\Response
     */
    public function closureCoupon()
    {
        $user_id = request('user_id');
        $coupon = $this->couponRepository->find(request('coupon_id'));
        if (($coupon->user_id != $user_id) OR $coupon->used_at) {
            return $this->api([], false, 400, '优惠券不存在');
        }

        $coupon->used_at = Carbon::now();
        $coupon->save();
        return $this->api();

    }
}